﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MouseLineRenderer : Actor 
{
    public LineRenderer m_LineRenderer;
    public float        m_RefreshRate = 0f;

    private bool        m_OnTouchDown = false;
    private int         m_NumberOfPoints = 0;
    private Vector3     m_MousePosition;
    private Vector3     m_PreviousPointPosition;

    private float       m_NewPointTimer = 0;
    private float       m_TimeSinceLineStart = 0;

    private int         m_NumberOfStaticPoints;

    private List<Vector3> m_PointsPosition;
    public List<Vector3> PointsPosition
    {
        get { return m_PointsPosition; }
    }

    public delegate void Callback();
    public Callback m_OnLineStart;
    public Callback m_OnLineEnd;

    private void Start () 
    {
        InputManager.OnTouchDown += OnTouchDown;
        InputManager.OnTouchUp += OnTouchUp;

        m_PointsPosition = new List<Vector3>();
	}
	
    private void FixedUpdate () 
    {
        if( m_OnTouchDown ) 
        {
            if(m_NewPointTimer > m_RefreshRate)
            {
                m_NewPointTimer = 0;
                
                m_MousePosition = Input.mousePosition;
                m_MousePosition.z = 1.0f;
                m_MousePosition = Camera.main.ScreenToWorldPoint(m_MousePosition);

                /*
                if(m_NumberOfPoints > 0 && m_NumberOfPoints < 10 && m_MousePosition.y <= m_PointsPosition[m_NumberOfPoints - 1].y)
                {
                    m_NumberOfStaticPoints++;
                }

                if(m_NumberOfStaticPoints >= 10)
                {
                    ResetLine();
                    return;
                }
                */

                m_NumberOfPoints++;
                m_LineRenderer.SetVertexCount( m_NumberOfPoints );

                m_LineRenderer.SetPosition(m_NumberOfPoints - 1, m_MousePosition);

                m_PointsPosition.Add(m_MousePosition);
            }

            m_TimeSinceLineStart += Time.deltaTime;
            m_NewPointTimer += Time.deltaTime;
        }
        else 
        {
            ResetLine();
        }
    }

    private void ResetLine()
    {
        m_NewPointTimer = m_RefreshRate + 1f;
        m_NumberOfStaticPoints = 0;
        m_NumberOfPoints = 0;
        m_LineRenderer.SetVertexCount(0);
        m_PointsPosition.Clear();
    }

    private void OnTouchDown()
    {
        m_OnTouchDown = true;
        if(m_OnLineStart != null) m_OnLineStart();
    }
    private void OnTouchUp()
    {
        m_OnTouchDown = false;
        if(m_OnLineStart != null) m_OnLineEnd();
    }

}
